package com.toymate.ai.tts.model.azure;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import com.microsoft.cognitiveservices.speech.SpeechConfig;
import com.microsoft.cognitiveservices.speech.SpeechSynthesisOutputFormat;
import com.microsoft.cognitiveservices.speech.SpeechSynthesisResult;
import com.microsoft.cognitiveservices.speech.SpeechSynthesizer;
import com.toymate.ai.tts.AbstractTtsService;
import com.toymate.ai.tts.TtsConfig;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.util.Optional;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * AzureTtsService
 *
 * @author weirdor (179946422@qq.com)
 * @version v1.0.0
 */
@Slf4j
public class AzureTtsService extends AbstractTtsService {

    private static final Lock lock = new ReentrantLock();

    public AzureTtsService(TtsConfig config) {
        this.config = config;
    }

    public static String generateFilePath() {
        lock.lock();
        try {
            String tmpDir = System.getProperty("java.io.tmpdir");
            String uniqueId = IdUtil.getSnowflakeNextIdStr();
            return tmpDir + uniqueId + ".mp3";
        } finally {
            lock.unlock();
        }
    }

    /**
     * 文字转换语音
     *
     * @param content 转换的文字
     * @return Optional<String> 文件路径
     */
    @Override
    public Optional<String> speechSynthesizer(String id, String content) {
        try {
            String key = config.getAzureTtsConfig().getKey();
            String serviceRegion = config.getAzureTtsConfig().getServiceRegion();
            String voiceName = config.getAzureTtsConfig().getVoiceName();
            String filePath = generateFilePath();
            SpeechConfig speechConfig = SpeechConfig.fromSubscription(key, serviceRegion);//key,地区
            speechConfig.setSpeechSynthesisLanguage("zh-CN");//语言
            speechConfig.setSpeechSynthesisVoiceName(voiceName);//语言名称
            speechConfig.setSpeechSynthesisOutputFormat(SpeechSynthesisOutputFormat.Audio16Khz32KBitRateMonoMp3);
            SpeechSynthesizer synthesizer = new SpeechSynthesizer(speechConfig, null);
            SpeechSynthesisResult result = synthesizer.SpeakText(content);
            byte[] audioData = result.getAudioData();
            File f = new File(filePath);
            FileUtil.writeBytes(audioData, f);
            return Optional.of(filePath);
        } catch (Exception e) {
            log.error("AzureTtsService speechSynthesizer error", e);
        }
        return Optional.empty();
    }
}
